package com.tansun.easycare.rule.decisiontree.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.tansun.easycare.rule.common.enums.RuleModelTypeFileEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.tansun.easycare.core.utils.ResponseTable;
import com.tansun.easycare.rule.common.ResMessage;
import com.tansun.easycare.rule.common.RuleBaseController;
import com.tansun.easycare.rule.common.model.ResponseVO;
import com.tansun.easycare.rule.common.model.SelectModelVo;
import com.tansun.easycare.rule.common.web.model.ProjectInfo;
import com.tansun.easycare.rule.datamodel.entity.RuleDataparams;
import com.tansun.easycare.rule.datamodel.service.DataModelService;
import com.tansun.easycare.rule.decisiontree.entity.DecisionTreeEntity;
import com.tansun.easycare.rule.decisiontree.model.RuleTreeManageVO;
import com.tansun.easycare.rule.decisiontree.service.DecisionTreeService;
import com.tansun.easycare.rule.rulemange.entity.RuleManage;
import com.tansun.easycare.rule.rulemange.model.RuleManageVO;
import com.tansun.easycare.rule.rulemange.service.RuleManageService;
import com.tansun.rule.common.RuleModelTypeEnum;
import com.tansun.rule.utils.LoggerManager;

/**
 * 决策树节点信息Controller
 *
 * @author lxs
 * @version 2017-03-08
 */
@RestController
@RequestMapping(value = "/ruleProj/decisionTree")
public class DecisionTreeController extends RuleBaseController {
    @Autowired
    private RuleManageService ruleManageService;
    @Autowired
    private DecisionTreeService decisionTreeService;

    /**
     * 进入决策树管理列表
     *
     * @param projectCode 规则项目编码
     * @param param       收集搜索参数
     * @return 路径
     */
    @RequestMapping("index")
    public ResponseVO index(@RequestBody RuleManageVO param) throws Exception {
        param.setModelType(RuleModelTypeEnum.DecisionTree.getCode());
        PageInfo<RuleManageVO> page = this.ruleManageService.findRuleManageVO(param.getPage(), param);
        ResponseTable<RuleManageVO>  resVo  = new  ResponseTable<RuleManageVO>(page);  
        return resVo;
    }

    @Autowired
    private DataModelService dataModelService;
    /**
     * 新建决策树模型
     *
     * @param tree 决策树模型
     * @return 是否操作成功对象
     */
    @RequestMapping("saveOrUpdateDecisionTree")
    public ResponseVO saveOrUpdateDecisionTree(@RequestBody RuleManage tree) throws Exception {
    	ResponseVO ret = new ResponseVO();
        try {
            Integer num = this.ruleManageService.countListFindName(tree, RuleModelTypeFileEnum.DecisionTree.type);
            if (num != null && num>0) {
                ret.setStatus(ResponseVO.ERROR);
                ret.setDescription("变量名称重复，请使用其他有效名称");
                return ret;
            }
            decisionTreeService.saveOrUpdateDecisionTree(tree);
            //dataModelService.saveOrUpdateBuiltinParam(tree.getCode(),tree.getName(), RuleModelTypeEnum.DecisionTree.code, tree.getProjectCode());
        } catch (Exception e) {
            LoggerManager.error(e.getMessage(), e, this.getClass());
            ret.setStatus(ResponseVO.ERROR);;
            ret.setDescription(e.getMessage());
        }
        return ret;
    }

    /**
     * 进入决策树详情页面
     *
     * @param decisionTreeId 决策树ID
     * @param isedit         是否编辑（display，edit）
     * @param version        版本号
     * @return 详情页面路径
     */
    @RequestMapping("detail")
    public ResponseVO detail(@RequestBody ProjectInfo projectInfo) throws Exception {
        RuleTreeManageVO  ruleTree  = decisionTreeService.getTreeInfo(projectInfo.getManageId(), projectInfo.getVersion(),projectInfo.getProjectCode(), projectInfo.getTemp());
        ruleTree.setVersion(projectInfo.getVersion());     
        ruleTree.setRankRelationId(projectInfo.getRankRelationId());
        ruleTree.setIsedit(projectInfo.getIsedit());
        ResponseVO  res  = new ResponseVO();
        res.setData(ruleTree);
        return res;
    }

    /**
     * 条件细分节点编辑OR新增弹出框
     */
    @RequestMapping("getDecisionSubNodeInfo")
    public String getDecisionSubNodeInfo(HttpServletRequest request, String decisionId, String openType, @RequestParam(value = "version", required = false) String version, String isLeft, ModelMap map) throws Exception {
        map.put("projectCode", this.getCurrProjectCode());
        map.put("decisionId", decisionId);
        map.put("openType", openType);
        map.put("version", version);
        map.put("isLeft", isLeft);
        return "/rule/decisiontree/decisionTreeDialog";
    }
    
    @RequestMapping("getTreeRefModel")
    public  String getTreeRefModel(HttpServletRequest request, String decisionId, String openType, @RequestParam(value = "version", required = false) String version, String isLeft, ModelMap map) throws Exception {
        map.put("projectCode", this.getCurrProjectCode());
        map.put("decisionId", decisionId);
        map.put("openType", openType);
        map.put("version", version);
        map.put("isLeft", isLeft);
        return "/rule/decisiontree/ruleRefModelDialog";
    }
    
    
    @RequestMapping("findRuleModel")
    public  ResponseVO  findRuleModel(@RequestBody  RuleManage  ruleManage) {
    	ResponseVO  res  = new  ResponseVO();
    	String  projectCode  =  ruleManage.getProjectCode();
    	String  modelType  = ruleManage.getModelType();
    	RuleManage  ruleInfo  = new  RuleManage();
    	ruleInfo.setProjectCode(projectCode);
    	ruleInfo.setModelType(modelType);
    	ruleInfo.setActiveFlag("1");
    	try {
     	   List<SelectModelVo> retList   = new  ArrayList<>();	
     	   SelectModelVo  seleModelVo  = null;
     	   if (RuleModelTypeEnum.FunctionParam.code.equals(modelType)) {
     		   Map<String,String> map  = new HashMap<String, String>();
     		   map.put("projectCode", projectCode);
     		   List<RuleDataparams> pList = this.decisionTreeService.findFunctionParam(map);
     		   for (RuleDataparams dataParam:pList) {
     			  seleModelVo  = new  SelectModelVo();
     			  seleModelVo.setCode(dataParam.getId());
     			  seleModelVo.setName(dataParam.getChzn());
     			  retList.add(seleModelVo);
     		   }
     	   }else {   
	    	   List<RuleManage>  list  =	this.ruleManageService.findList(ruleInfo);
	    	   java.util.Iterator<RuleManage> iter  =null;
	    	   RuleManage  rMan =null;
	    	
	
	    	   for ( iter=list.iterator();iter.hasNext();) {
	    		   rMan = iter.next();
	    		   if (rMan.getId().equals(ruleManage.getId())) {
	    		
	    		   }else {
		    		   seleModelVo  = new  SelectModelVo();
		    		   seleModelVo.setCode(rMan.getCode());
		    		   seleModelVo.setName(rMan.getName());
		    		   retList.add(seleModelVo);
	    		   }
	    	   }
     	   }
    	   res.setData(retList);
    	}catch (Exception e) {
    		res.setStatus(ResponseVO.ERROR);
			res.setDescription(e.getMessage());
		}
    	return res;
    	
    }
    
//    @ResponseBody
//    @RequestMapping("findReleModelList")
//    public  List<RuleReleModel> findReleModelList(@RequestParam(value = "nodeId", required = false) String nodeId,ModelMap map){
//    	   return  this.ruleReleModelService.findReleModelList(nodeId);
//    	   
//    }

    /**
     * 保存或更新决策树信息
     *
     * @param treeEntity 决策树信息收集（包含决策树模型，决策树节点信息）
     * @return 是否保存成功对象，若有异常，则会返回异常信息
     */
    @RequestMapping("saveOrUpdate")
    public ResponseVO saveOrUpdate(@RequestBody DecisionTreeEntity treeEntity) throws Exception {
    	ResponseVO ret = new ResponseVO();
        try {

            decisionTreeService.saveOrUpdate(treeEntity);
            dataModelService.saveOrUpdateBuiltinParam(treeEntity.getRuleManage().getCode(),treeEntity.getRuleManage().getName(),RuleModelTypeEnum.DecisionTree.code, treeEntity.getRuleManage().getProjectCode(),treeEntity.getRuleManage().getCreateBy());
        } catch (Exception e) {
            LoggerManager.error(e.getMessage(), e, this.getClass());
            ret.setStatus(ResponseVO.ERROR);
            ret.setDescription(e.getMessage());
        }
        return ret;
    }

    /**
     * 显示java代码
     *
     * @param treeEntity 决策树信息收集（包含决策树模型，决策树节点信息）
     * @return java代码
     */
    @RequestMapping("showJavaCode")
    public @ResponseBody
    ResMessage showJavaCode(@RequestBody DecisionTreeEntity treeEntity) throws Exception {
    	ResMessage res = new ResMessage();
    	String javacode = decisionTreeService.showJavaCode(treeEntity);
        res.setCode("success");
        res.setMsg(javacode);
        return res;
    }
    
    @Override
    public void setRuleBizService() {
        // TODO Auto-generated method stub
        super.setRuleBaseService(decisionTreeService);
    }


}